import asyncio
import re
import logging
from urllib.parse import urlparse
from typing import List, Dict, Optional
import feedparser  # pip install feedparser  # RSS解析库

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def extract_rss(content: str) -> Optional[str]:
    """
    从 HTML 内容中提取 RSS 标签内容

    参数:
    content (str): HTML 内容

    返回:
    str | None: RSS 内容
    """
    # 匹配 <rss> 标签及内容
    rss_regex = re.compile(r'(<rss[\s\S]*?</rss>)', re.IGNORECASE)
    matches = rss_regex.search(content)
    return matches.group(0) if matches else None


async def parse_rss(rss_content: str) -> List[Dict[str, str]]:
    """
    解析 RSS 内容（支持 URL/XML 字符串），返回 RSS 数据

    """

    def is_url(url: str) -> bool:
        try:
            result = urlparse(url)
            return all([result.scheme in ["http", "https"], result.netloc])
        except ValueError:
            return False

    try:
        feed = feedparser.parse(rss_content) if is_url(rss_content) else feedparser.parse(rss_content)

        if feed.bozo:  # 新增错误检查
            logger.error(f"❌ RSS格式错误: {feed.bozo_exception}")
            return []

        return [{
            'title': item.get('title', ''),
            'link': item.link,
            'pubDate': item.get('published', ''),
            'author': item.get('author', item.get('creator', '')),
            'content': item.get('description', ''),
            'contentSnippet': item.get('contentSnippet', ''),
            'guid': item.get('guid', ''),
            'categories': item.get('tags', [])
        } for item in feed.entries]
    except Exception as e:
        logger.error(f"❌ [RSS] 解析失败: {str(e)}")
        return []


# ----------------------------------------------------------------------------------------------------------------------
async def main():
    try:
        valid_rss = '''<?xml version="1.0"?>
    <rss version="2.0">
    <channel>
        <title>示例频道</title>
        <item>
            <title>测试文章</title>
            <link>https://example.com</link>
        </item>
    </channel>
    </rss>'''

        print("解析字符串:", await parse_rss(valid_rss))
        print("解析URL:", await parse_rss("http://feeds.bbci.co.uk/news/rss.xml"))  # 真实测试URL
    except Exception as e:
        logger.error(f"测试失败: {str(e)}")


if __name__ == '__main__':
    asyncio.run(main())
